# coding=utf-8
import json
from datetime import datetime, timedelta

from flask import jsonify

from blues.cloud import bp
from blues.cloud.base import request_asapi
from database2 import db_exec_many
from model.c_department import find_all_depart
from model.c_eip import find_eip_info_by_id


def record_cms_eip() -> bool:
    # 取昨日最后的监控数据时间
    start_time = (datetime.today() - timedelta(days=1)).strftime('%Y-%m-%d 00:00:00')
    end_time = (datetime.today() - timedelta(days=1)).strftime('%Y-%m-%d 23:59:59')

    # 1 对于专有云，通过部门ak sk获取当前组织监控数据
    depart_list = find_all_depart()
    # 初始化一个空数组，在循环中不断追加
    values_list = []
    # 初始化一个空字典，用于存放带宽使用数据
    res = {}
    for depart in depart_list:
        cloud_id = depart['cloud_id']
        depart_id = depart['department']
        depart_name = depart['department_name']
        depart_ak = depart['access_key_id']
        depart_sk = depart['access_key_secret']

        # 获取ASAPI接口数据
        params = {
            "Namespace": "acs_vpc_eip",
            "MetricName": "net_rx.rate",
            "Period": "900",
            "StartTime": start_time,
            "EndTime": end_time,
        }
        asapi_data = request_asapi(cloud_id, "Cms", "2019-01-01", "DescribeMetricList", params, depart_ak, depart_sk)
        # print(asapi_data)
        if not asapi_data:
            return False
        data_points = json.loads(asapi_data['Datapoints'])

        # 准备批量插入数据库，先初始化一个空数组，在循环中不断追加
        values_list = []

        # 批量预处理带宽监控数据，插入到以实例为id的字典中
        for i in data_points:
            ins_id = i['instanceId']
            net_rx = i['Value']
            if ins_id not in res.keys():
                res[ins_id] = {
                    "cloud_id": cloud_id, "depart_id": depart_id, "depart_name": depart_name,
                    "net_rx": [net_rx], "net_rx_max": [], "net_rx_min": [], "net_rx_avg": []
                }
                continue
            res[ins_id]["net_rx"].append(net_rx)
        # print(res)

        # 将规整到字典里的数据，求max min avg
        for ins_id in res.keys():
            res[ins_id]["net_rx_max"] = max(res[ins_id]["net_rx"]) if res[ins_id]["net_rx"] else 0
            res[ins_id]["net_rx_min"] = min(res[ins_id]["net_rx"]) if res[ins_id]["net_rx"] else 0
            res[ins_id]["net_rx_avg"] = round(sum(res[ins_id]["net_rx"]) / len(res[ins_id]["net_rx"]), 0)

    # 遍历字典，进行字段汇总处理,并存放到最终字典里
    for ins_id in res.keys():
        eip_info = find_eip_info_by_id(ins_id)
        # 数据库里没找到实例信息的，直接忽略
        if eip_info == {}:
            continue
        eip_bandwidth = int(eip_info['bandwidth'])
        tmp_tuple = (
            ins_id, res[ins_id]['cloud_id'], res[ins_id]['depart_id'], res[ins_id]['depart_name'],
            res[ins_id]['net_rx_max'], res[ins_id]['net_rx_min'], res[ins_id]['net_rx_avg'],
            eip_bandwidth, end_time, datetime.now()
        )
        values_list.append(tmp_tuple)

    # 使用上面的数据，批量插入db
    table = 'cms_eip'
    fields = "instance_id,cloud_id,department,department_name,net_rx_max,net_rx_min,net_rx_avg,bandwidth,date,record_time"
    db_success = db_exec_many(table, fields, values_list)
    if not db_success:
        return False
    return True


@bp.route('/api/v1/cloud/record_cms_eip', methods=['POST'])
def record_cms_eip_api():
    success = record_cms_eip()
    if not success:
        return jsonify({'code': 500})
    return jsonify({'code': 200})
